const http = require('http');

module.exports = class Express {
    constructor() {
        this.routes = {};
        this.middlewares = [];
    }

    use(middleware) {
        this.middlewares.push(middleware);
    }

    get(path, callback) {
        this.routes[path] = callback;
    }

    handleRequest(req, res) {
        let index = -1;
        const next = () => {
            index++;
            const middleware = this.middlewares[index];
            if (middleware) {
                middleware(req, res, next);
            } else {
                const callback = this.routes[req.url];
                if (callback) {
                    callback(req, res);
                } else {
                    res.statusCode = 404;
                    res.end('Not Found');
                }
            }
        };
        next();
    }

    listen(port, callback) {
        const server = http.createServer(this.handleRequest.bind(this));
        server.listen(port, callback);
    }
}
